package com.gaxy.auth.common.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登陆上下文对象
 *
 * @author Gaxy
 * @create 2024/06/21/下午 03:50
 */
public class LoginContextHolder {

    //继承机制，子线程可以从父线程那里继承线程局部变量的值，用于传递上下文信息
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL
            = new InheritableThreadLocal<>();


    public static void set(String key, Object val){
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, val);
    }

    public static Object get(String key){
        Map<String, Object> map = getThreadLocalMap();
        return map.get(key);
    }

    public static void remove(){
        THREAD_LOCAL.remove();
    }

    public static String getLoginId(){
        return (String)getThreadLocalMap().get("loginId");
    }

    public static Map<String, Object> getThreadLocalMap(){
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)){
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
